package fr.labri.harmony.analysis.jsep.results.filter;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import fr.labri.harmony.analysis.jsep.results.LoadRules;

public class MigrationLoopbackBounce extends ResultFilter {

	@Override
	public void computeResult(ResultSet rs) throws SQLException, IOException {
		Map<String,List<String>> rules = new HashMap<String, List<String>>();
		while (rs.next()){		
			String project = rs.getString("PROJECT");
			String source = rs.getString("NAME");
			String target = rs.getString("MIGRATION_LIB_TO");
			if(LoadRules.isTrueRule(source, target)) {
				String when =  rs.getString("MIGRATION_START_NUMBER")+"_"+rs.getString("INTRO_OUT_NUMBER");
				if(!rules.containsKey(project)) rules.put(project, new ArrayList<String>());
				rules.get(project).add(when+"_"+source+"_"+target);
			}
		}

		for(String project : rules.keySet()) {
			if(rules.get(project).size() > 1) {
				Map<Integer,Set<String>> index = new HashMap<Integer, Set<String>>();
				Map<Integer,Set<String>> index_t = new HashMap<Integer, Set<String>>();
				boolean ok = false;
				for(String rule : rules.get(project)){
					int i = LoadRules.getRuleCat(rule.split("\\_")[2], rule.split("\\_")[3]);
					if(!index.containsKey(i)) index.put(i, new HashSet<String>());
					index.get(i).add(rule.split("\\_")[2]);
					if(!index_t.containsKey(i)) index_t.put(i, new HashSet<String>());
					index_t.get(i).add(rule.split("\\_")[3]);
				}
				for(int i : index.keySet()) {
					if(index.get(i).size() > 1 && index_t.get(i).size() > 1)
						ok=true;
				}
				if(ok) {
					System.out.println("*****");
					System.out.println("\t"+project+"\t"+index);
					Collections.sort(rules.get(project));
					for(String rule : rules.get(project))
						System.out.println("\t\t"+rule);
				}
			}
		}

	}

}
